<template>
  <a-card class="general-card">
    <div class="stats-header">
      <div class="title">每日打卡热力图</div>
      <!--      <div class="stats-grid">-->
      <!--        <div class="stats-item">-->
      <!--          <div class="stats-icon solved">-->
      <!--            <icon-check-circle />-->
      <!--          </div>-->
      <!--          <div class="stats-value">42</div>-->
      <!--          <div class="stats-label">总提交</div>-->
      <!--        </div>-->
      <!--        <div class="stats-item">-->
      <!--          <div class="stats-icon streak">-->
      <!--            <icon-trophy />-->
      <!--          </div>-->
      <!--          <div class="stats-value">26</div>-->
      <!--          <div class="stats-label">通过数</div>-->
      <!--        </div>-->
      <!--        <div class="stats-item">-->
      <!--          <div class="stats-icon rate">-->
      <!--            <icon-arrow-rise />-->
      <!--          </div>-->
      <!--          <div class="stats-value">61.9%</div>-->
      <!--          <div class="stats-label">通过率</div>-->
      <!--        </div>-->
      <!--      </div>-->
    </div>
    <div class="stats-section">
<!--      <div class="section-title">每日打卡热力图</div>-->
      <div class="heatmap-container">
        <div class="heatmap-wrapper">
          <div class="month-labels">
            <span v-for="month in months" :key="month">{{ month }}月</span>
          </div>
          <div class="heatmap-grid">
            <div
              v-for="(cell, index) in heatmapData"
              :key="index"
              class="heatmap-cell"
              :class="getCellClass(cell.count)"
              @mousemove="showTooltip(cell, $event)"
              @mouseleave="hideTooltip"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="tooltipVisible"
      class="tooltip"
      :style="{
        left: tooltipPosition.x + 'px',
        top: tooltipPosition.y + 'px'
      }"
    >
      <div class="tooltip-date">{{ currentCell?.date }}</div>
      <div class="tooltip-count">{{ currentCell?.count }} 次提交</div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <a-spin />
    </div>
  </a-card>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import axios from 'axios';
import { Message } from '@arco-design/web-vue';
import {
  IconCheckCircle,
  IconTrophy,
  IconArrowRise
} from '@arco-design/web-vue/es/icon';

interface HeatmapCell {
  date: string;
  count: number;
}

interface Position {
  x: number;
  y: number;
}

const tooltipVisible = ref(false);
const currentCell = ref<HeatmapCell | null>(null);
const tooltipPosition = ref<Position>({ x: 0, y: 0 });
const heatmapData = ref<HeatmapCell[]>([]);
const months = ref<number[]>([]);
const loading = ref(false);

// 生成最近5个月的月份标签
const generateMonths = () => {
  const currentMonth = dayjs().month() + 1;
  months.value = [];
  for (let i = 4; i >= 0; i--) {
    let month = currentMonth - i;
    if (month <= 0) month += 12;
    months.value.push(month);
  }
};

// 从后端获取热力图数据
const fetchHeatmapData = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/oj/heatmap/submission', {
      params: { days: 55 }
    });
    if (response.data.code === 200 && response.data.result) {
      heatmapData.value = response.data.result;
    } else {
      Message.error('获取提交记录失败: ' + (response.data.message || '未知错误'));
      // 如果API请求失败，使用空数据代替
      generateEmptyHeatmapData();
    }
  } catch (error) {
    console.error('获取热力图数据错误:', error);
    Message.error('获取提交记录失败');
    // 如果API请求出错，使用空数据代替
    generateEmptyHeatmapData();
  } finally {
    loading.value = false;
  }
};

// 生成空的热力图数据（API请求失败时使用）
const generateEmptyHeatmapData = () => {
  const data: HeatmapCell[] = [];
  const endDate = dayjs();
  const startDate = endDate.subtract(55, 'day');

  for (let i = 0; i < 55; i++) {
    const date = startDate.add(i, 'day');
    data.push({
      date: date.format('YYYY-MM-DD'),
      count: 0
    });
  }

  heatmapData.value = data;
};

const getCellClass = (count: number) => {
  if (count === 0) return 'level-0';
  if (count <= 3) return 'level-1';
  if (count <= 6) return 'level-2';
  return 'level-3';
};

const showTooltip = (cell: HeatmapCell, event: MouseEvent) => {
  currentCell.value = cell;
  tooltipVisible.value = true;

  const target = event.target as HTMLElement;
  const rect = target.getBoundingClientRect();
  const cardRect = target.closest('.general-card')?.getBoundingClientRect();

  if (cardRect) {
    const cellCenterX = rect.left - cardRect.left + rect.width / 2;
    const cellTopY = rect.top - cardRect.top;

    tooltipPosition.value = {
      x: cellCenterX,
      y: cellTopY - 5
    };
  }
};

const hideTooltip = () => {
  tooltipVisible.value = false;
};

onMounted(() => {
  generateMonths();
  fetchHeatmapData();
});
</script>

<style scoped lang="less">
.general-card {
  border-radius: 16px;
  padding: 8px;
  position: relative;
  background-color: var(--color-bg-2);
  height: auto;
}

.stats-header {
  margin-bottom: 8px;

  .title {
    font-size: 16px;
    font-weight: 500;
    color: var(--color-text-1);
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--color-border-2);
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  background-color: var(--color-fill-1);
  padding: 8px;
  border-radius: 8px;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stats-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2px;

  &.solved {
    background-color: rgba(57, 102, 162, 0.1);
    color: #3966a2;
  }

  &.streak {
    background-color: rgba(255, 182, 0, 0.1);
    color: #ffb600;
  }

  &.rate {
    background-color: rgba(154, 193, 240, 0.1);
    color: #9ac1f0;
  }
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--color-text-1);
}

.stats-label {
  font-size: 13px;
  color: var(--color-text-3);
}

.stats-section {
  background-color: var(--color-fill-1);
  border-radius: 8px;
  padding: 8px;

  .section-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text-1);
    margin-bottom: 8px;
  }
}

.heatmap-container {
  padding: 0;
}

.heatmap-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.month-labels {
  display: flex;
  justify-content: space-between;
  padding: 0 4px;
  color: var(--color-text-3);
  font-size: 12px;
}

.heatmap-grid {
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  gap: 4px;
}

.heatmap-cell {
  aspect-ratio: 1;
  border-radius: 2px;
  background-color: #ebedf0;
  transition: all 0.2s ease;
  cursor: pointer;
  position: relative;

  &.level-0 {
    background-color: #ebedf0;
  }

  &.level-1 {
    background-color: rgba(57, 102, 162, 0.3);
  }

  &.level-2 {
    background-color: rgba(57, 102, 162, 0.6);
  }

  &.level-3 {
    background-color: #3966a2;
  }

  &:hover {
    transform: scale(1.25);
    z-index: 2;
  }
}

.tooltip {
  position: absolute;
  background-color: #3966a2;
  border-radius: 6px;
  padding: 6px 8px;
  pointer-events: none;
  z-index: 1000;
  transform: translate(-50%, -100%);
  white-space: nowrap;

  &::after {
    content: '';
    position: absolute;
    bottom: -4px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    width: 8px;
    height: 8px;
    background-color: #3966a2;
  }

  &-date {
    color: white;
    font-size: 13px;
    font-weight: 500;
    text-align: center;
  }

  &-count {
    color: white;
    font-size: 12px;
    text-align: center;
  }
}

.loading-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.5);
  z-index: 10;
}
</style>
